package searchcode;

public class BinaryChange {
    public static void main(String[] args) {
        int[] arr = {1, 5, 13, 22, 22, 22, 67, 89};
        int index = binaryChange01(arr, 221);
        System.out.println(index);
        index = binaryChange02(arr, 221);
        System.out.println(index);
        arr = new int[]{1, 5, 13, 23, 24, 25, 67, 89};
        index = binaryChange03(arr, 24);
        System.out.println(index);
        index = binaryChange04(arr, 24);
        System.out.println(index);
    }

    // 1.有重复元素找出第一个重复项索引
    public static int binaryChange01(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (arr[mid] < target) {
                low = mid + 1;
            } else if (arr[mid] > target) {
                high = mid - 1;
            } else {
                if (mid == 0 || arr[mid - 1] != target) return mid;
                else high = mid - 1;
            }
        }
        return -1;
    }

    // 2.有重复元素找出最后一个重复项索引
    public static int binaryChange02(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (arr[mid] < target) {
                low = mid + 1;
            } else if (arr[mid] > target) {
                high = mid - 1;
            } else {
                if (mid == high || arr[mid + 1] != target) return mid;
                else low = mid + 1;
            }
        }
        return -1;
    }

    // 3.无重复元素，找出第一个大于等于target的值
    public static int binaryChange03(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (arr[mid] < target) {
                low = mid + 1;
            } else {
                if (mid == 0 || arr[mid - 1] < target) return mid;
                else high = mid - 1;
            }
        }
        return -1;
    }

    // 4.无重复元素，最后一个小于等于target的索引
    public static int binaryChange04(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        while (low <= high){
            int mid = (low+high) / 2;
            if (arr[mid] > target){
                high = mid - 1;
            }else {
                if(mid == high || arr[mid+1]>target) return mid;
                else low = mid + 1;
            }
        }
        return -1;
    }
}
